<?php

class Application_Model_Mapper_BewertungenMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Bewertungen');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Bewertungen $object)
	{		

		$now = new DateTime();
		
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
			$data = array(
					'id' => $generatedid,
					'created' => date('Y-m-d H:i:s'),
					'locationid' => $object->getLocationid(),
					'erstellerid' =>  $object->getErstellerid(),
					'titel' => $object->getTitel(),
					'anzschiffe'=> $object->getAnzschiffe(),
					'bewertung' => $object->getInhalt()
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($object);
		}
		
	}
	
	public function update(Application_Model_Bewertungen $object)
	{
		
		$data = array(
				'titel' => $object->getTitel(),
				'anzschiffe' => $object->getAnzschiffe(),
				'bewertung' => $object->getBewertung()
		);

		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $object->getId());
		$table->update($data, $where);
	}
	

	public function delete ($id)
	{
 		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $id);
		$table->delete($where);
	}

	public function fetchID ($id){
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bewertungen');
		$entry->where('bewertungen.id = ?', $id);
		return $entry->query()->fetch();
	}
	
	public function fetchAll(){
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bewertungen');
		return $entry->query()->fetchall();
	}

}




